import type { IDictItem } from "@/types";

import axios from "axios";
import { onMounted, onUnmounted, reactive, ref } from "vue";
import { message } from "ant-design-vue";
import { useLocalStorage } from "@vueuse/core";
import router from "@/router";

export const dict = ref([] as IDictItem[]);

export const host = import.meta.env.DEV ? "http://localhost:2025" : "http://124.70.134.192:2025";

export const filePath = "https://www.alan.plus/"
export const token: globalThis.Ref<string> = useLocalStorage("token", "");


/**
 * 从数据库里查询字典数据
 */
export const queryAndSetGlobalDict = async () => {
  const res = await post("dict/get");
  dict.value = res?.data ?? [];
};

/**
 * 根据id获取单个字典（用于查找字典名）
 * @param id
 */
export const getDictType = (id: number = -1) => {
  return dict.value.find((item) => item.id === id) as any;
};
/**
 * 获取所有字典
 */
export const getDictAll = () => {
  return dict.value;
};

/**
 * 获取字典名（键值转换）
 * @param kind
 * @param value
 * @param emptyLabel
 */
export const getDictText = (kind: string, value: string, emptyLabel: string = "没有找到字典项"): string | number => {
  const foundKind = dict.value?.find((item) => item.key === kind);
  const foundItem = foundKind?.children?.find((item) => item.key === value);
  return foundItem?.name ?? `${emptyLabel} (${kind} - ${value})`;
};
/**
 * 获取字典键值对（筛选时使用）
 * @param kind
 */
export const getDictList = (kind: string): IDictItem[] => {
  const foundKind = dict.value?.find((item) => item.key === kind);
  return foundKind?.children ?? [];
};
/**
 * 获取字典键值对（返回option下拉框选项）
 * @param kind
 */
export const getDictListToOptions = (kind: string) => {
  const foundKind = dict.value?.find((item) => item.key === kind);
  return foundKind?.children?.map((item) => ({
    label: item.name,
    value: item.key,
  }));
};

/**
 * 程序休眠方法
 * @param timeout
 */
export const sleep = (timeout: number = 0) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(null);
    }, timeout);
  });
};

/**
 * 注销（清空token并跳转登录页）
 */
export const logout = () => {
  token.value = "";
};

/**
 * 后端接口转发
 * @param data
 * @param config
 */
export const crossPost = async (data: any, config: any = undefined) => {
  const api = data.url
  let configNew: any = { headers: { token: `Bearer ${token.value }`} };
  const whiteApi = [
    //
    "alanlogin",
    "register",
    "dict/get",
    "user/getAllUser",
  ];
  if (!whiteApi.includes(api) && !token.value) {
    // token为空
    logout();
  } else if (whiteApi.includes(api) || api.includes("white")) {
    configNew = {};
  }
  if (typeof data === "string" || typeof data === "number") {
    configNew = { ...configNew, headers: { "Content-Type": "text/plain", token: token.value } };
  }
  if (config) {
    configNew = { ...configNew, ...config };
  }
  const res = await axios.post(`${host}/v1/cross`, data, configNew).catch((err) => {
    if (err?.response?.data?.code === 2100001) {
      // 登录验证失败
      logout();
    }
    message.error(`访问${api}出错,${err}`);
    return Promise.reject(err);
  });
  return res.data;
}
/**
 * 全局通用post方法
 * @param api
 * @param data
 * @param config
 */
export const post = async (api: string, data: any = {}, config: any = undefined) => {
  let configNew: any = { headers: { } };
  const whiteApi = [
    //
    "login",
    "register",
    "dict/get",
    "user/getAllUser",
  ];
  if (!whiteApi.includes(api) && !token.value) {
    // token为空
    logout();
  } else if (whiteApi.includes(api) || api.includes("white")) {
    configNew = {};
  }
  if (typeof data === "string" || typeof data === "number") {
    configNew = { ...configNew, headers: { "Content-Type": "text/plain" } };
  }
  if (config) {
    console.log("是");
    configNew = { ...configNew, ...config };
    console.log(configNew);
  }
  const res = await axios.post(`${host}/${api}`, data, configNew).catch((err) => {
    if (err?.response?.data?.code === 2100001) {
      // 登录验证失败
      logout();
    }
    message.error(`访问${api}出错,${err}`);
    return Promise.reject(err);
  });
  return res.data;
};

/**
 * 去除stable水印（只能去除右下角的）
 */
export const deleteWatermark = async () => {
  let domArr = document.querySelectorAll(".surely-table div");
  await sleep(1);
  for (let i = 0; i < domArr.length; i++) {
    let node = domArr.item(i) as HTMLElement;
    if (["Unlicensed Product"].includes(node.innerText)) {
      node.remove();
    }
    if (["mysure", "Powered by Surely Vue"].includes(node.innerText)) {
      node.innerHTML = "";
    } else if (["mysure"].includes("")) {
      node.innerHTML = "success!";
    }
  }
};

/**
 * 获取响应式窗口高度
 * @param drop 差值调整
 */
export const useReactiveHeight = (drop: number = 0) => {
  const reactiveHeight = ref(0);
  const setReactiveHeightHeight = () => {
    const setHeight = () => (reactiveHeight.value = window.innerHeight - 180 + drop);
    onMounted(() => {
      setHeight();
      window.addEventListener("resize", setHeight);
    });
    onUnmounted(() => {
      window.removeEventListener("resize", setHeight);
    });
  };
  setReactiveHeightHeight();
  return reactiveHeight;
};
